<script setup lang="ts">
// 任务列表页面 - 从ZenPathTask.vue迁移过来
import { ref, onMounted, nextTick } from 'vue';
import { apiGet, apiPost, apiPatch } from '@/request/apiUtils';
import axios from 'axios';
import moment from 'moment';
import { ElMessage } from 'element-plus'
const formatDate = (d: any) => moment(d).format('YYYY-MM-DD');

const if_extension_list: TObj = {
    1: '是',
    0: '否',
}

// 任务状态选项
const statusOptions = ref([] as string[])

// 责任人选项
const responsiblePersonOptions = ref([] as string[])
const filteredResponsiblePersonOptions = ref([] as string[])
// 产品经理选项
const productManagerOptions = ref<string[]>([]);
const filteredProductManagerOptions = ref<string[]>([]);
const taskTypeOptions = ref<string[]>([]);
const initQuery = {
    task_id: undefined,
    epic_name: undefined,
    story_name: undefined,
    task_name: undefined,
    task_type: undefined,
    fc_responsible_person: undefined,
    project: undefined,
    status: undefined,
    fc_publish_version: undefined,
    product_manager: undefined,
    task_data: undefined,
};
const initForm = {
      id: null,
      task_id: null,
      epic_name: null,
      story_name: null,
      fc_publish_version: null,
      product_manager: null,
    task_name: null,
    task_type: null,
    project: null,
    status: null,
    fc_responsible_person: null,
    estimate_time: null,
    fc_plan_start_time: null,
    fc_plan_end_time: null,
    fc_actual_start_time: null,
    fc_actual_end_time: null,
}
const { value: state } = ref({
    loading: false,
    tableData: [] as TObj[],
    total: 0,
    pageSize: 10,
    currentPage: 1,
    queryData: { ...initQuery },
    maxtime: "",
    mintime: "",
    gantter_status: false,
    table_span: 24,
    gantt_span: 12,
    showDialog: false,
    isCreate: false,
    form: { ...initForm },
    dialogLoading: false,
    total_hours: 0  // 任务工时总和
});


const myBarList = ref([] as TObj[])
const startTime = ref([] as TObj[])
const endTime = ref([] as TObj[])
const tableRef = ref(null)
const ganttRef = ref(null)

// 获取责任人列表
const fetchResponsiblePersons = async () => {
    try {
        const response: TObj = await apiGet('/tasks/responsible_persons');
        responsiblePersonOptions.value = response?.results || [];
        filteredResponsiblePersonOptions.value = response?.results || [];
    } catch (error) {
        console.error('Error fetching responsible persons:', error);
    }
}

// 获取产品经理列表
const fetchProductManagers = async () => {
    try {
        const response: TObj = await apiGet('/tasks/product_managers');
        productManagerOptions.value = response?.results || [];
        filteredProductManagerOptions.value = response?.results || [];
    } catch (error) {
        console.error('Error fetching product managers:', error);
    }
}

// 获取任务状态列表
const fetchTaskStatuses = async () => {
    try {
        const response: TObj = await apiGet('/tasks/task_statuses');
        statusOptions.value = response?.results || [];
    } catch (error) {
        console.error('Error fetching task statuses:', error);
    }
}

// 获取任务类型列表
const getTaskTypes = async () => {
    try {
        const response: TObj = await apiGet('/tasks/task_types');
        taskTypeOptions.value = response?.results || [];
    } catch (error) {
        console.error('获取任务类型列表失败:', error);
    }
}

const fetchData = async (page = state.currentPage, size = state.pageSize) => {
    state.loading = true;
    try {
        const apiUrl = '/tasks';
        
        // 重新构建查询参数
        const params: TObj = {
            page,
            size
        };
        
        // 添加所有非空查询参数
        Object.keys(state.queryData).forEach(key => {
            const value = state.queryData[key];
            // 只添加非undefined、非null、非空字符串的参数
            if (value !== undefined && value !== null && value !== '') {
                if (key === 'task_data' && Array.isArray(value) && value.length === 2) {
                    // 处理日期范围
                    params.task_start_data = formatDate(value[0]);
                    params.task_end_data = formatDate(value[1]);
                } else if (key === 'task_type' && Array.isArray(value) && value.length > 0) {
                    // 处理多选任务类型，将数组转换为逗号分隔的字符串
                    params[key] = value.join(',');
                } else if (key === 'status' && Array.isArray(value) && value.length > 0) {
                    // 处理多选状态，将数组转换为逗号分隔的字符串
                    params[key] = value.join(',');
                } else if (key === 'fc_responsible_person' && Array.isArray(value) && value.length > 0) {
                    // 处理多选责任人，将数组转换为逗号分隔的字符串
                    params[key] = value.join(',');
                } else if (key === 'product_manager' && Array.isArray(value) && value.length > 0) {
                    // 处理多选产品经理，将数组转换为逗号分隔的字符串
                    params[key] = value.join(',');
                } else if (key !== 'task_data') {
                    params[key] = value;
                }
            }
        });
        
        console.log('查询参数:', params);
        const response: TObj = await apiGet(apiUrl, params);
        state.tableData = response?.results || [];
        state.total = response?.count || 0;
        state.total_hours = response?.total_hours || 0;

        myBarList.value = []
        startTime.value = []
        endTime.value = []
        // 确保甘特图行数和表格行数一一对应
        for (let i in state.tableData) {
            let startDate = state.tableData[i]['fc_plan_start_time'];
            let endDate = state.tableData[i]['fc_plan_end_time'];

            // 将结束日期设置为结束日期的下一天 00:00，确保包含结束日期整天
            // 例如：2025-10-17 到 2025-10-18，应该显示为 2025-10-17 00:00 到 2025-10-19 00:00
            // 这样就能完整显示17日和18日两天
            let endDateForGantt = endDate;
            if (endDate) {
                endDateForGantt = moment(endDate).add(1, 'days').format('YYYY-MM-DD');
            }

            // 无论是否有日期，都要为每一行数据创建对应的甘特图行，确保一一对应
            const bar = [{
                myBeginDate: startDate ? startDate + " 00:00" : null,
                myEndDate: endDateForGantt ? endDateForGantt + " 00:00" : null,
                ganttBarConfig: {
                    id: state.tableData[i]['task_id'] || '',
                    label: state.tableData[i]['task_name'] || ''
                }
            }]

            // 收集日期用于计算时间范围
            if (state.tableData[i]['fc_plan_start_time'] != null) {
                startTime.value.push(state.tableData[i]['fc_plan_start_time'])
            }
            if (state.tableData[i]['fc_plan_end_time'] != null) {
                endTime.value.push(state.tableData[i]['fc_plan_end_time'])
            }
        }

        // 计算甘特图的时间范围
        if (startTime.value.length > 0 && endTime.value.length > 0) {
            state.mintime = moment(Math.min(...startTime.value.map(d => new Date(d).getTime()))).format('YYYY-MM-DD')
            state.maxtime = moment(Math.max(...endTime.value.map(d => new Date(d).getTime()))).format('YYYY-MM-DD')
        } else {
            // 如果没有数据，使用当前日期前后30天作为默认范围
            state.mintime = moment().subtract(30, 'days').format('YYYY-MM-DD')
            state.maxtime = moment().add(30, 'days').format('YYYY-MM-DD')
        }

        console.log('甘特图时间范围:', state.mintime, state.maxtime)

        // 确保甘特图在DOM更新后重新渲染
        nextTick(() => {
            if (ganttRef.value) {
                ganttRef.value.refresh()
            }
        })

    } catch (error) {
        console.error('Error fetching data:', error);
        ElMessage({
            message: '获取数据失败',
            type: 'error',
        })
    } finally {
        state.loading = false;
    }
}

// 责任人搜索过滤方法
const filterResponsiblePerson = (query: string) => {
    if (query) {
        filteredResponsiblePersonOptions.value = responsiblePersonOptions.value.filter(person =>
            person.toLowerCase().includes(query.toLowerCase())
        );
    } else {
        filteredResponsiblePersonOptions.value = [...responsiblePersonOptions.value];
    }
}

// 产品经理搜索过滤方法
const filterProductManager = (query: string) => {
    if (query) {
        filteredProductManagerOptions.value = productManagerOptions.value.filter(person =>
            person.toLowerCase().includes(query.toLowerCase())
        );
    } else {
        filteredProductManagerOptions.value = [...productManagerOptions.value];
    }
}

// 页数改变
const handleSizeChange = (val: number) => {
    state.pageSize = val;
    fetchData(state.currentPage, val);
}

const handleCurrentChange = (val: number) => {
    state.currentPage = val;
    fetchData(val, state.pageSize);
}

// 重置
const handleReset = () => {
    state.queryData = { ...initQuery };
    fetchData();
}

// 查询
const handleSearch = () => {
    state.currentPage = 1;
    fetchData(1, state.pageSize);
}

// 打开弹窗
const openDialog = (isCreate = true, rowItem?: TObj) => {
    state.isCreate = isCreate;
    state.showDialog = true;
    if (isCreate) {
        state.form = { ...initForm };
    } else {
        state.form = { ...rowItem };
    }
}

// 关闭弹窗
const closeDialog = () => {
    state.showDialog = false;
}

// 保存表单
const saveForm = async () => {
    state.dialogLoading = true;
    try {
        if (state.isCreate) {
            const apiUrl = `/tasks/`;
            await apiPost(apiUrl, state.form);
            ElMessage({
                message: '新增成功',
                type: 'success',
            })
        } else {
            const apiUrl = `/tasks/${state.form.id}/`;
            await apiPatch(apiUrl, state.form);
            ElMessage({
                message: '修改成功',
                type: 'success',
            })
        }
        closeDialog();
        fetchData(state.currentPage, state.pageSize);
    } catch (error) {
        console.error(error);
        ElMessage({
            message: state.isCreate ? '新增失败' : '修改失败',
            type: 'error',
        })
    } finally {
        state.dialogLoading = false;
    }
}

// 删除任务
const handleDelete = async (rowItem: TObj) => {
    try {
        const apiUrl = `/tasks/${rowItem.id}/`;
        const response = await apiGet(apiUrl, {
            method: 'DELETE'
        });
        if (response?.code === 200) {
            ElMessage({
                message: '删除成功',
                type: 'success',
            })
            fetchData(state.currentPage, state.pageSize);
        } else {
            throw new Error('删除失败');
        }
    } catch (error) {
        console.error(error);
        ElMessage({
            message: '删除失败',
            type: 'error',
        })
    }
}

onMounted(() => {
    fetchResponsiblePersons();
    fetchProductManagers();
    fetchTaskStatuses();
    getTaskTypes();
    fetchData();
});
</script>

<template>
  <div class="zen-path-task">
    <!-- 搜索区域 -->
    <div class="search-area">
      <div class="search-inner">
        <el-select 
          v-model="state.queryData.fc_responsible_person" 
          placeholder="责任人" 
          class="width200" 
          multiple 
          clearable 
          filterable
          :filter-method="filterResponsiblePerson">
          <el-option v-for="person in filteredResponsiblePersonOptions" :key="person" :label="person" :value="person" />
        </el-select>
        
        <el-select 
          v-model="state.queryData.product_manager" 
          placeholder="产品经理" 
          class="width200" 
          multiple 
          clearable 
          filterable
          :filter-method="filterProductManager">
          <el-option v-for="pm in filteredProductManagerOptions" :key="pm" :label="pm" :value="pm" />
        </el-select>
        
        <el-select 
          v-model="state.queryData.status" 
          placeholder="任务状态" 
          class="width200" 
          multiple 
          clearable>
          <el-option v-for="status in statusOptions" :key="status" :label="status" :value="status" />
        </el-select>
        
        <el-date-picker
          v-model="state.queryData.task_data"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          class="width300"
        >
        </el-date-picker>
        
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="statistics-info">
      <el-card>
        <div class="info-item">
          <span class="label">总任务数量：</span>
          <span class="value">{{ state.total }}</span>
        </div>
        <div class="info-item">
          <span class="label">总工时：</span>
          <span class="value">{{ state.total_hours }}</span>
        </div>
      </el-card>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table 
        :data="state.tableData" 
        border 
        style="width: 100%;" 
        v-loading="state.loading">
        <el-table-column prop="task_id" label="任务ID" width="150" />
        <el-table-column prop="epic_name" label="史诗" width="200" />
        <el-table-column prop="story_name" label="故事" width="200" />
        <el-table-column prop="task_name" label="任务名称" width="300" />
        <el-table-column prop="task_type" label="任务类型" width="120" />
        <el-table-column prop="project" label="项目" width="150" />
        <el-table-column prop="fc_responsible_person" label="责任人" width="150" />
        <el-table-column prop="status" label="状态" width="120" />
        <el-table-column prop="fc_publish_version" label="版本" width="120" />
        <el-table-column prop="product_manager" label="产品经理" width="150" />
        <el-table-column prop="estimate_time" label="预估工时" width="120" />
        <el-table-column prop="fc_plan_start_time" label="计划开始时间" width="180" />
        <el-table-column prop="fc_plan_end_time" label="计划结束时间" width="180" />
        <el-table-column prop="fc_actual_start_time" label="实际开始时间" width="180" />
        <el-table-column prop="fc_actual_end_time" label="实际结束时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="openDialog(false, scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-area">
        <span class="total-count">共 {{ state.total }} 条记录</span>
        <el-pagination 
          v-model:currentPage="state.currentPage" 
          v-model:page-size="state.pageSize"
          :page-sizes="[10, 20, 50, 100]" 
          size="small" 
          layout="sizes, prev, pager, next, jumper" 
          :total="state.total" 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- 弹窗 -->
    <el-dialog
      v-model="state.showDialog"
      title="任务详情"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="closeDialog"
    >
      <el-form :model="state.form" label-width="120px" class="dialog-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="任务ID">
              <el-input v-model="state.form.task_id" placeholder="请输入任务ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务名称">
              <el-input v-model="state.form.task_name" placeholder="请输入任务名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务类型">
              <el-select v-model="state.form.task_type" placeholder="请选择任务类型">
                <el-option v-for="type in taskTypeOptions" :key="type" :label="type" :value="type" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目">
              <el-input v-model="state.form.project" placeholder="请输入项目" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="责任人">
              <el-select v-model="state.form.fc_responsible_person" placeholder="请选择责任人">
                <el-option v-for="person in responsiblePersonOptions" :key="person" :label="person" :value="person" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品经理">
              <el-select v-model="state.form.product_manager" placeholder="请选择产品经理">
                <el-option v-for="pm in productManagerOptions" :key="pm" :label="pm" :value="pm" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select v-model="state.form.status" placeholder="请选择状态">
                <el-option v-for="status in statusOptions" :key="status" :label="status" :value="status" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="版本">
              <el-input v-model="state.form.fc_publish_version" placeholder="请输入版本" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预估工时">
              <el-input v-model="state.form.estimate_time" type="number" placeholder="请输入预估工时" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划开始时间">
              <el-date-picker
                v-model="state.form.fc_plan_start_time"
                type="date"
                placeholder="请选择计划开始时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划结束时间">
              <el-date-picker
                v-model="state.form.fc_plan_end_time"
                type="date"
                placeholder="请选择计划结束时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实际开始时间">
              <el-date-picker
                v-model="state.form.fc_actual_start_time"
                type="date"
                placeholder="请选择实际开始时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实际结束时间">
              <el-date-picker
                v-model="state.form.fc_actual_end_time"
                type="date"
                placeholder="请选择实际结束时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="史诗">
              <el-input v-model="state.form.epic_name" placeholder="请输入史诗" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="故事">
              <el-input v-model="state.form.story_name" placeholder="请输入故事" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="saveForm" :loading="state.dialogLoading">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.zen-path-task {
  padding: 20px;
}

.search-area {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-inner {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.width200 {
  width: 200px;
}

.width300 {
  width: 300px;
}

.statistics-info {
  margin-bottom: 20px;
}

.info-item {
  display: inline-block;
  margin-right: 30px;
}

.label {
  font-weight: bold;
  margin-right: 5px;
}

.value {
  font-size: 18px;
  color: #409eff;
}

.table-area {
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
}

.pagination-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 10px 0;
}

.total-count {
  color: #606266;
  font-size: 14px;
}

.dialog-form {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>